import ProductAPI from '@/api/Product';
import { Box, FieldCols, FieldTable, FormSection, useCall, useFormValue, useQueryValue, useReq } from '@/components';
import { DroolsRulesField } from '@/pages/components';
import { getQueryValues, pathJoin } from '@/utils';
import { catchAndScrollFor } from '@/utils/fp';
import { Button, Form, message, Space, Spin, Table, Modal } from 'antd';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { AttributePoolFields, Context, data2Form, form2Data } from './components';
import * as FIELDS from './components/FIELDS';
import ResponsibilityForm from './responsibilityForm'

function Provider({ form, children }) {
  const productCode = useFormValue(form, ['productAddVo', 'productAttrVo', 'productCode']);

  const ctx = useMemo(() => ({ form, productCode }), [productCode]);

  return <Context.Provider value={ctx}>{children}</Context.Provider>;
}

function AddBasicProducts({ history, location }) {
  const businessCode = useQueryValue('businessCode');
  const productCode = useQueryValue('productCode');
  const isCopy = useQueryValue('action') === 'copy';

  const [form] = Form.useForm();
  const originalDataRef = useRef(null);
  const xhr = useReq(ProductAPI.getInfo);
  const copyXhr = useReq(ProductAPI.getCopy);
  const saveXhr = useReq(ProductAPI.insertOrUpdate);
  const [isModalVisible, setIsModalVisible] = useState(false);


  const handleOk = () => {
    // setIsModalVisible(false);
    handleResponsibilityOk()
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  const handleResponsibility = (row, type) => {
    setIsModalVisible(true);
    console.log(row, type, 'rowwww')
  };
  const handleResponsibilityOk = (value) => {
    console.log(value, 'valuevaluevalue')
  }

  const dataSource = [
    {
      key: '1',
      name: '胡彦斌',
      age: 32,
      address: '西湖区湖底公园1号',
    },
    {
      key: '2',
      name: '胡彦祖',
      age: 42,
      address: '西湖区湖底公园1号',
    },
  ];

  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'key',
      render: (recode, row, index) => {
        console.log(recode, row, index, 'recode,row,index')
        return (
          <div>{index + 1}</div>
        )
      }
    },
    {
      title: '责任ID',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '责任名称',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '是否必选',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: '维护关系',
      dataIndex: 'name',
      key: 'name',
      render: (recode, row, index) => <div style={{ color: 'blue', cursor: 'pointer' }} onClick={() => handleResponsibility(row, "relationship")}>维护关系</div>
    },
    {
      title: '责任配置',
      dataIndex: 'name',
      key: 'name',
      render: (recode, row, index) => <div style={{ color: 'blue', cursor: 'pointer' }} onClick={() => handleResponsibility(row, "duty")}>责任配置</div>
    }
  ];

  useEffect(() => {
    if (isCopy) {
      copyXhr.start(productCode, businessCode);
    } else if (businessCode) {
      xhr.start(businessCode);
    } else {
      form.resetFields();
    }
  }, []);

  useEffect(() => {
    if (copyXhr.result?.data) {
      originalDataRef.current = JSON.parse(JSON.stringify(copyXhr.result.data));
      const [companyCode, companyName] = getQueryValues(location.search, 'companyCode', 'companyName');
      const formData = data2Form(copyXhr.result.data);
      if (companyCode) {
        formData.productAddVo.productAttrVo.companyCode = companyCode;
        formData.productAddVo.productAttrVo.companyName = companyName;
      }
      form.setFieldsValue(formData);
    }
  }, [copyXhr.result]);

  useEffect(() => {
    if (xhr.result?.data) {
      originalDataRef.current = JSON.parse(JSON.stringify(xhr.result.data));
      form.setFieldsValue(data2Form(xhr.result.data));
    }
  }, [xhr.result]);

  const handleSave = useCall(async () => {
    const values = await form.validateFields().catch(catchAndScrollFor(form));
    const data = form2Data(values, originalDataRef.current);
    await saveXhr.start(data);
    message.success('保存成功');
    history.replace(pathJoin(location.pathname, '../'));
  });

  const loading = [xhr.status, copyXhr.status, saveXhr.status].includes('loading');

  return (
    <Provider form={form}>
      <Spin spinning={loading}>
        <Form form={form}>
          <FormSection title='基本信息'>
            <FieldCols form={form} fields={FIELDS.basic} />
          </FormSection>

          <FormSection title='投保条件'>
            <FieldCols form={form} fields={FIELDS.condition} />
          </FormSection>

          <FormSection title='保额/保费'>
            <FieldCols form={form} fields={FIELDS.premium} />
          </FormSection>

          <AttributePoolFields />

          <FormSection title='豁免'>
            <FieldCols form={form} fields={FIELDS.exemption} />
          </FormSection>

          <FormSection title='保费&缴费'>
            <FieldTable
              form={form}
              name='premPay'
              fields={FIELDS.premPay}
              showRemoveBtn
              showAddBtn
              scrollY='max(240px, min(720px, calc(100vh - 320px)))'
            />
          </FormSection>

          {/*<FormSection title='条款'>
           <FieldTable form={form} name='clause' fields={FIELDS.clause} showRemoveBtn showAddBtn />
           </FormSection>*/}

          <FormSection title='规则'>
            <DroolsRulesField name='droolsRules' />
          </FormSection>

          {/* 暂时接口没有 */}
          {/* <FormSection title='投保人规则'>
            <FieldCols form={form} fields={FIELDS.holderRule} />
          </FormSection> */}

          <FormSection title='计算'>
            <FieldCols form={form} fields={FIELDS.formula} />
          </FormSection>

          <FormSection title='责任'>
            <Table dataSource={dataSource} columns={columns} pagination={false} />
          </FormSection>

          {/* productCategory === 'MC' */}
          {/* <DutyFields /> */}
        </Form>
        <Modal width={800} visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
          <ResponsibilityForm onResponsibilityOk={() => handleResponsibilityOk(value)} />
        </Modal>

        <Box flex jus='center' py={3} className='form-page-btn'>
          <Space size='large'>
            <Button onClick={history.goBack}>返回</Button>
            <Button type='primary' onClick={handleSave}>
              保存
            </Button>
          </Space>
          <Box py={1} />
        </Box>
      </Spin>
    </Provider>
  );
}

AddBasicProducts.title = '基础险种管理 险种编辑';

export default AddBasicProducts;
